jQuery(document).ready(function(){
	var arr = jQuery("#myarrow");
	var arrX =  arr.offset();
	console.log("onready");
	var timer,running = false;

	var slope = function(e){
		//console.log(e.pageX+" "+e.pageY+" "+arrX.left+" "+arrX.top);
		var tx = parseInt(e.pageX,10)-40;
		var ty = parseInt(e.pageY,10)-parseInt(arrX.top,10);
		var m = ty/tx;
		return m;
	};
	jQuery("div.action").mousemove(function(e){
		if(!running){
			var m = slope(e);
			//console.log("slope "+m);
			m = Math.atan(m)*180/Math.PI;
			m = 'rotate('+m+'deg)';
			//console.log("M = "+m);
			arr.css('-webkit-transform',m);
		};
	}).mouseup(function(e){
		console.log("mouse up "+running);
		if(running)return;
		var m = slope(e);
		var b = parseInt(e.pageY,10) - parseInt(m*parseInt(e.pageX,10),10);
		var angle = Math.atan(m)*180/Math.PI;
		console.log("b = "+b);
		angle = 'rotate('+m+'deg)';
		arr.css('-webkit-transform',angle);
		var x = 40;
		var value = parseInt(document.getElementById('race').value,10);
		var widthOfWindow = parseInt(jQuery(window).width(),10);
		timer = window.setInterval(function(){
			if(parseInt(x,10)>= (widthOfWindow-60)){
				console.log("out "+timer+" "+running);
				window.clearInterval(timer);
				window.setTimeout(function(){
					arr.css('left',0);
					arr.css('top',"50%");
					running = false;
					},1000);
				return;
			};
			running = true;
			console.log(" interval "+x+ " "+value);
			x = parseInt(x,10);
			x+= value;
			var y = parseInt(m*x,10) + b; 
			arr.css('top',y+'px');
			arr.css('left',x+'px');
		},100);
	});
});